package coop.bancocredicoop.proyectos.gd.query.document;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.Transaction;

import coop.bancocredicoop.proyectos.gd.domain.Customer;
import coop.bancocredicoop.proyectos.gd.domain.Document;
import coop.bancocredicoop.proyectos.gd.domain.DocumentType;
import coop.bancocredicoop.proyectos.gd.hibernate.HibernateUtil;

public class FindVersions {

	public List<Document> run(Customer customer, DocumentType documentType)
			throws Exception {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		List<Document> listResult = null;

		try {
			tx = session.beginTransaction();

			listResult = _run(customer, documentType, session);

			tx.commit();
		}
		catch (Exception e) {
			if (tx!=null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		return listResult;

	}

	private List<Document> _run(Customer customer, DocumentType documentType,
			Session session) throws Exception {

		String strQuery = " from Document " +
				" where deleteDate is null " +
				" and customer = :customer " +
				" and documentType = :documentType " +
				" order by realVersion desc ";

		Query query = session.createQuery(strQuery);

		query.setEntity("customer", customer);
		query.setEntity("documentType", documentType);

		return query.list();

	}

}
